package com.weilai.service.serviceImpl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weilai.dao.*;
import com.weilai.domain.Comments;
import com.weilai.domain.Likes;
import com.weilai.domain.User;
import com.weilai.domain.Videos;
import com.weilai.service.CommentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    private CommentsDao commentsDao;
    @Autowired
    PostsDao postsDao;
    @Autowired
    VideosDao videosDao;

    @Override
    @Transactional
    public Map<String, Object> like(int userId, int commentsId) {
        Map<String, Object> result = new HashMap<>();
        int count = commentsDao.countUserLiked(userId, commentsId);
        if (count == 0) {
            commentsDao.incrementLikeCount(commentsId);
            commentsDao.insertLikeRecord(userId, commentsId);
            result.put("message", "点赞成功");
        } else {
            result.put("message", "已点赞过此评论");
        }
        // 获取更新后的点赞数
        int likeCount = commentsDao.getLikeCount(commentsId);
        result.put("likeCount", likeCount);
        return result;
    }

    @Override
    @Transactional
    public Map<String, Object> cancelLike(int userId, int commentsId) {
        Map<String, Object> result = new HashMap<>();
        // 直接尝试删除点赞记录，无需先查询
        int rows = commentsDao.deleteLikeRecord(userId, commentsId);
        if (rows > 0) {
            commentsDao.decrementLikeCount(commentsId);
            result.put("message", "取消点赞成功");
        } else {
            result.put("message", "未找到点赞记录");
        }
        // 获取更新后的点赞数
        int likeCount = commentsDao.getLikeCount(commentsId);
        result.put("likeCount", likeCount);
        return result;
    }
    @Override
    public int isLikedByUser(int userId, int commentsId) {
        int count = commentsDao.countUserLiked(userId, commentsId); // DAO层已提供该方法
        if(count == 0){
            return 0;
        }
        return 1;
    }
    //评论分页
    @Override
    public PageInfo<Comments> getCommentsByPostIdWithPaging(int postId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(postsDao.getCommentsByPostId(postId));
    }

    @Override
    public PageInfo<Comments> getCommentsByVideoIdWithPaging(int video, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return new PageInfo<>(videosDao.getCommentsByVideoId(video));
    }

    // 根据用户id删除评论
    @Override
    public int deleteCommentByUserId(int userId){
        return commentsDao.deleteCommentByUserId(userId);
    }

}


